package ferp.android.tasks.center;

import android.os.AsyncTask;
import ferp.center.client.Action;
import ferp.center.network.request.RequestGameReportSend;
import ferp.core.Version;
import ferp.core.game.Game;
import ferp.core.log.Log;
import ferp.core.player.Profile;

/**
 * User: igorgok
 * Date: 10/26/12 5:03 PM
 */
public class TaskGameReportSend extends AsyncTask<Void, Void, Boolean>
{
  public interface Listener
  {
    void onSendingGameReportStart();
    void onSendingGameReportEnd(boolean success);
  }

  public TaskGameReportSend(Profile profile, Version version, String email, String description, Exception exception, Listener listener)
  {
    this.profile = profile;
    this.version = version;
    this.email = email;
    this.description = description;
    this.exception = exception;
    this.listener = listener;
  }

  @Override
  protected void onPreExecute()
  {
    if (listener != null)
      listener.onSendingGameReportStart();
  }

  @Override
  protected Boolean doInBackground(Void... voids)
  {
/*
    if (BuildConfig.DEBUG)
      return true;

*/
    try
    {
      RequestGameReportSend request = new RequestGameReportSend(profile, version.toString(), email, description, exception, Game.gson);

      return Action.execute(Action.GAME_REPORT_ADD, request, Boolean.class);
    }
    catch (Exception e)
    {
      Log.error(Action.TAG, e);
    }

    return false;
  }

  @Override
  protected void onPostExecute(Boolean result)
  {
    if (listener != null)
      listener.onSendingGameReportEnd(result == null ? false : result);

    if (exception != null && aborted == 0)
      ++aborted;
  }

  private static int aborted = 0;

  private final Profile profile;
  private final Version version;
  private final String email;
  private final String description;
  private final Exception exception;
  private final Listener listener;
}
